package com.example.mqttmanage.config;

import com.example.mqttmanage.domain.user.User;
import com.example.mqttmanage.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service // 标记为 Spring Bean，这是关键！
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库查询用户
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("username", username);
        
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException("User not found: " + username);
        }

        // 将数据库中的 User 转换为 Spring Security 的 UserDetails
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword()) // 数据库中存储的已加密密码
                .authorities("ROLE_USER") // 示例角色，可根据实际业务逻辑设置
                .accountExpired(false)      // 账户未过期
                .accountLocked(false)       // 账户未锁定
                .credentialsExpired(false)  // 凭证未过期
                .build();
    }
}